import pickle
import os
from selenium import webdriver
from time import  sleep
# 大麦网主页
damai_url = "https://m.damai.cn/damai/home/index.html"
# 登录页
login_url = "https://m.damai.cn/damai/minilogin/index.html?returnUrl=https%3A%2F%2Fm.damai.cn%2Fshows%2Fmine.html%3Fspm%3Da2o71.home.top.duserinfo&spm=a2o71.mydamai.0.0"
# 抢票目标页
target_url = 'https://detail.damai.cn/item.htm?spm=a2oeg.search_category.0.0.77f24d15RWgT4o&id=654534889506&clicktitle=%E5%A4%A7%E4%BC%97%E7'


class Concert:
    def __init__(self):
        options = webdriver.ChromeOptions()
        options.add_argument("--disable-blink-features=AutomationControlled")
        options.add_argument("user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1")
        # 指定设备名称即可
        options.add_experimental_option('mobileEmulation', {'deviceName': 'iPhone X'})
        self.status = 0         # 状态,表示如今进行到何种程度
        self.login_method = 1   # {0:模拟登录,1:Cookie登录}自行选择登录方式
        self.driver = webdriver.Chrome(options=options)        # 默认Chrome浏览器
        # 读取文件
        with open('stealth.min.js', 'r') as f:
            js = f.read()
        # 调用函数在页面加载前执行脚本
        self.driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': js})


    def set_cookie(self):
        self.driver.get(damai_url)
        print("###请点击登录###")
        self.driver.get(login_url)
        while self.driver.title.find('登录') != -1:
            sleep(1)
        print('###请验证码登录###')

        while self.driver.title != '登录':
           sleep(1)
        print("###验证码成功###")
        pickle.dump(self.driver.get_cookies(), open("cookies.pkl", "wb"))
        print("###Cookie保存成功###")
        self.driver.get(target_url)

    def get_cookie(self):
        try:
            cookies = pickle.load(open("cookies.pkl", "rb"))  # 载入cookie
            for cookie in cookies:
                cookie_dict = {
                    'domain': '.damai.cn',  # 必须有，不然就是假登录
                    'name': cookie.get('name'),
                    'value': cookie.get('value')
                }
                self.driver.add_cookie(cookie_dict)
            print('###载入Cookie###')
        except Exception as e:
            print(e)

    def login(self):
            if self.login_method == 0:
                self.driver.get(login_url)
                # 载入登录界面
                print('###开始登录###')

            elif self.login_method == 1:
                if not os.path.exists('cookies.pkl'):
                    # 如果不存在cookie.pkl,就获取一下
                    self.set_cookie()
                else:
                    print(111)
                    self.driver.get(target_url)
                    self.get_cookie()


    def enter_concert(self):
        """打开浏览器"""
        print('###打开浏览器，进入大麦网###')
        self.driver.maximize_window()  # 最大化窗口
        self.driver.refresh()
        # 调用登陆
        self.login()  # 先登录再说
        # self.driver.refresh()                   # 刷新页面
        self.status = 2  # 登录成功标识
        print("###登录成功###")


    def enter_concert(self):
        """打开浏览器"""
        print('###打开浏览器，进入大麦网###')
        self.driver.maximize_window()  # 最大化窗口
        # 调用登陆
        self.login()  # 先登录再说
        # self.driver.refresh()                   # 刷新页面
        self.status = 2  # 登录成功标识
        print("###登录成功###")

    def choose_ticket(self):
        if self.status == 2:  # 登录成功入口
            print("=" * 30)
            print("###检查是否开始售票###")
            while not self.isElementExistByClass('buy-link'):
                self.driver.refresh()
                print("###售票尚未开始,刷新等待开始###")
            # TODO 选择票型
            # ========begin=========

            # ========end===========
            self.driver.find_element(By.CLASS_NAME, 'buy-link').click()  # 点击购票二维码下的购买连接
            sleep(1.5)
            self.check_order()


    def check_order(self):
        if self.status == 2:
            print('###开始确认订单###')
            if self.driver.title == '订单确认页':
                print('###检查是否需要填写观影人')
                if self.isElementExistByXPATH('//*[@id="dmViewerBlock_DmViewerBlock"]'):
                    self.driver.find_element(By.XPATH, '//*[@id="dmViewerBlock_DmViewerBlock"]/div[2]/div/div').click()
                    sleep(0.5)
                print('###跳转支付选择界面###')
                self.driver.find_element(By.XPATH,
                                         '//*[@id="dmOrderSubmitBlock_DmOrderSubmitBlock"]/div[2]/div/div[2]/div[2]/div[2]').click()
                sleep(2)
                self.pay_order()


    def pay_order(self):
        if self.driver.title == "支付宝付款":
            print('###支付订单###')
            if self.isElementExistByXPATH('//*[@id="app"]/div[3]/div[1]/button[2]'):
                self.driver.find_element(By.XPATH, '//*[@id="app"]/div[3]/div[1]/button[2]').click()
                print('###跳转至浏览器支付###')
                sleep(1.5)
                self.driver.find_element(By.XPATH, '//*[@id="app"]/div[3]/div/div[1]/div[2]/input').clear()
                self.driver.find_element(By.XPATH, '//*[@id="app"]/div[3]/div/div[1]/div[2]/input').send_keys(
                    '支付宝账号')  # 输入支付宝账号
                self.driver.find_element(By.XPATH, '//*[@id="app"]/div[3]/div/button').click()
                sleep(1.5)
                self.driver.find_element(By.XPATH, '//*[@id="app"]/div[2]/button').click()
                while True:
                    sleep(1)
                    print('###请输入支付密码###')

    def finish(self):
            self.driver.quit()


if __name__ == '__main__':
    try:
        con = Concert()  # 具体如果填写请查看类中的初始化函数
        con.enter_concert()  # 打开浏览器
        con.choose_ticket()  # 开始抢票

    except Exception as e:
        print(e)
        con.finish()
